import router from "./routers";
import store from "@/store";
import Config from "@/settings";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth"; // getToken from cookie
import { filterAsyncRouter } from "@/store/modules/permission";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ["/login", "/sss"]; // 不重定向白名单


router.beforeEach((to, from, next) => { 
  if (to.meta.title) {
    document.title = to.meta.title + " - " + Config.title;
  }
  NProgress.start();
  if (getToken()) {
    // 已登录且要跳转的页面是登录页
    // debugger
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done();
    } else {
      if (store.getters.roles.length === 0) {
        // 判断当前用户是否已拉取完user_info信息
        store
          .dispatch("GetInfo")
          .then(() => {
            // 拉取user_info
            console.log("GetInfo");
            // 动态路由，拉取菜单
            loadMenus(next, to);
          })
          .catch(res => {
            console.log(res);
            setTimeout(() => {
              store.dispatch("LogOut").then(() => {
                location.reload(); // 为了重新实例化vue-router对象 避免bug
              });
            }, 1000);
          });
        // 登录时未拉取 菜单，在此处拉取
      } else if (store.getters.loadMenus) {
        // 修改成false，防止死循环
        store.dispatch("updateLoadMenus");
        loadMenus(next, to);
      } else {
        next();
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
      NProgress.done();
      
    }
  }
});
// 获取到路由，并进行组装
export const loadMenus = (next, to) => {
  store.dispatch("GetInfo").then(res => {
    const rou = funRou(res.result.menus);
    const asyncRouter = filterAsyncRouter(rou);
    asyncRouter.push({ path: "*", redirect: "/404", hidden: true });
    store.dispatch("GenerateRoutes", asyncRouter).then(() => {
      // 存储路由
      router.addRoutes(asyncRouter); // 动态添加可访问路由表
      next({ ...to, replace: true });
    });
    store.dispatch('GenerateUserName', res.result.username);
  });
};

export const funRou = router => {
  let routerNew = {};
  const o_ul = [];
  let o_li = {};
  let c_ul = [];
  let c_li = {};
  for (let i = 0; i < router.length; i++) {
    if (router[i].child) {
      for (let j = 0; j < router[i].child.length; j++) {
        c_li = {
          component: router[i].child[j].component
            ? router[i].child[j].component.toString()
            : "Layout",
          hidden: false,
          meta: {
            title: router[i].child[j].title,
            icon: router[i].child[j].icon,
            noCache: true
          },
          name: router[i].child[j].title,
          path: router[i].child[j].route ? router[i].child[j].route : "/viewa"
        };
        c_ul.push(c_li);
      } 
    }
    o_li = {
      alwaysShow: true,
      children: c_ul,
      component: "Layout",
      hidden: false,
      meta: {
        title: router[i].title,
        icon: router[i].icon,
        noCache: true
      },
      name: router[i].title,
      // path: router[i].route,
      path: router[i].route ? router[i].route : "/viewa",
      redirect: "noredirect"
    };
    o_ul.push(o_li);
    c_ul = [];
  }
  routerNew = o_ul;
  return routerNew;
};

router.afterEach(() => {
  NProgress.done(); // 进度条
});
